-- 自减脚本，小于0返回[-1, 当前库存], key不存在会初始化为0.
local k = KEYS[1]
local n = ARGV[1] 
local num = redis.call("DECRBY", k, n)
local res = {}
res["code"] = 0
res["num"] = num

if num < 0 then
  num = redis.call("INCRBY", k, n)
  res["code"] = -1 
  res["num"] = num
end

return cjson.encode(res)